const Router = require('koa-router')
const router = new Router({ prefix: '/api' })
const { User } = require('../models/model')
const jwt = require('jsonwebtoken')
const crypto = require('crypto') // 加密模块

// 公共路由接口


router.post('/register', async (ctx, next) => {
  const body = ctx.request.body
  let pwd = body.password
  let md5 = crypto.createHash('md5') // md5加密
  let newPwd = md5.update(pwd).digest('hex')
  const data = await User.create({
    username: body.username,
    password: newPwd,
    rid: body.rid
  })
  if (data) {
    // 还要判断用户号是否已存在，还可以使用短信验证码注册用户
    ctx.status = 200
    ctx.body = {
      code: 200,
      msg: '新增用户成功',
      data: data
    }
  } else {
    ctx.status = 500
    ctx.body = {
      code: 500,
      msg: '新增用户失败',
      data: data
    }
  }
})

// 登录获取表单数据，判断用户名和密码是否存在并正确，正确生成 token 返回给前端
router.post('/login', async (ctx, next) => {
  // 使用 postman body row 的 json 格式测试获取数据
  const body = ctx.request.body
  let pwd = body.password
  let md5 = crypto.createHash('md5')
  let newPwd = md5.update(pwd).digest('hex')
  const user = await User.findOne({ 
    where: {
      username: body.username,
      password: newPwd
    }
  })
  if (user === null) {
    ctx.status = 0
    ctx.body = {
      code: 0,
      msg: '账号不存在或密码错误'
    }
  } else {
    ctx.session.username = body.username
    ctx.status = 200
    ctx.body = {
      code: 200,
      msg: '登录成功',
      token: jwt.sign({
        data: body.username,
        exp: Math.floor(Date.now() / 1000) + 60 * 60
      },
      'jwt_secret'
      )
    }
  }
})

module.exports = router